package com.wxx.design.hungrysingleton;

import java.io.*;
import java.lang.reflect.Constructor;

/**
 * @author Jetwang
 * @version 1.0
 * @date 2022/4/11 20:01
 */
public class Test {
    public static void main(String[] args) throws Exception {
        HungarySingleton instance = HungarySingleton.getInstance();
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("singleton_file"));
        oos.writeObject(instance);

        File file = new File("singleton_file");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));

        HungarySingleton newInstance  = (HungarySingleton)ois.readObject();
        System.out.println(instance);
        System.out.println(newInstance);
        // false 序列化和反序列化得到的对象不一样,序列化破坏了单例模式
        // 当实现了readResolve方法后，就解决了序列化破坏单例的问题
        System.out.println(instance == newInstance);


        // 反射破坏单例
        Class objectClass = HungarySingleton.class;
        Constructor constructor = objectClass.getDeclaredConstructor();
        // 设置可以访问私有
        constructor.setAccessible(true);
        HungarySingleton instance1 = HungarySingleton.getInstance();
        // 通过反射获得的构造器创建对象
        HungarySingleton instance2 = (HungarySingleton) constructor.newInstance();
        System.out.println(instance1);
        System.out.println(instance2);
        // 并非同一个对象
        System.out.println(instance1 == instance2);

    }
}
